<template>
    <!-- 委托人 -->
    <div class="e-table">
        <div class="top">
            <div class="left">
                <div>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="aptitudeAddRow"
                    >
                        添加
                    </el-button>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDownload"
                        v-if="isBatch"
                    >
                        批量下载
                    </el-button>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDelete"
                        v-if="isBatch"
                    >
                        批量删除
                    </el-button>
                </div>

                <div class="batchBox" @click="batchOperation">
                    <img class="batchicon" src="@/assets/piliang.png" />
                    <span class="batchfont">{{ batch }}</span>
                </div>
            </div>

            <div class="right" v-if="!isTableRowClass">
                <div class="squarecolor">
                    <div class="color colorAdd"></div>
                    <span>新增</span>
                </div>
                <div class="squarecolor item">
                    <div class="color colorUpdate"></div>
                    <span>修改</span>
                </div>
                <div class="squarecolor">
                    <div class="color colorDel"></div>
                    <span>删除/过期</span>
                </div>
            </div>
        </div>
        <div class="errorMsg" v-if="errorMsg.length > 0">
            <span
                style="display: block"
                v-for="(item, index) in errorMsg"
                :key="index"
            >
                {{ item }}
            </span>
        </div>
        <el-table
            :data="aptitudeTable"
            border
            style="width: 100%"
             :max-height="$store.state.tableHeight"
            @selection-change="handleDetailSelectionChange"
            @cell-click="cellClick"
            :row-class-name="tableRowClass"
            v-sortTable="{ 'tableData': aptitudeTable, '_this': this, 'ref': 'table' }"
            ref="table"
            class="table"
        >
            <el-table-column
                type="selection"
                width="55"
                v-if="isBatch"
            ></el-table-column>
            <el-table-column  label="序号" type="index" width="60">
            </el-table-column>
            <el-table-column fixed label="操作" width="60">
                <template slot-scope="{ row, $index }">
                    <div class="handle">
                        <img
                            v-if="row.changeType != -1"
                            src="@/assets/btn/delete.png"
                            @click="handleDelete(row, $index)"
                        />
                        <img
                            v-else
                            src="@/assets/btn/cancelDelete.png"
                            @click="revoke($index)"
                        />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="姓名" width="180" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    <el-input
                        @change="modifyState(row)"
                        v-model.trim="row.name"
                    ></el-input>
                </template>
            </el-table-column>
            <el-table-column label="手机号" width="180" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    <el-input
                        @change="modifyState(row)"
                        maxlength="11"
                        v-enterInteger1
                        v-model.trim="row.phone"
                        onkeyup="value=value.replace(/[^\d]/g,'')"
                        @blur="row.phone = $event.target.value"
                    ></el-input>
                </template>
            </el-table-column>
            <el-table-column label="身份证号" width="180" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    <el-input
                        @change="modifyState(row)"
                        maxlength="18"
                        v-model.trim="row.idCard"
                    ></el-input>
                </template>
            </el-table-column>
            <el-table-column
                prop="idCardOssName"
                label="身份证附件"
                min-width="200"
                show-overflow-tooltip
            >
                <template slot-scope="scope">
                    <span
                        @click="preview()"
                        style="color: blue; cursor: pointer; overflow: hidden"
                    >
                        {{ scope.row.idCardOssName }}
                    </span>
                    <el-upload
                        style="margin: 7px 15px 0px 0px"
                        class="upload-demo"
                        :action="uploadUrl"
                        :data="{
                            bucketName,
                            relationId,
                            orgCode
                        }"
                        :before-upload="beforeAvatarUpload"
                        :accept="accept"
                        :on-success="attachOnSuccessIdCard"
                        :http-request="uploadBeforeIdCard"
                        :show-file-list="false"
                        @change="modifyState(row)"
                        name="files"
                    >
                        <img src="@/assets/btn/commit.png" />
                    </el-upload>
                    <img
                     v-if="scope.row.id"
                        src="@/assets/btn/downLoad.png"
                        @click="handleDownload1(scope.row)"
                        style="position: absolute; right: 0;"
                    />
                </template>
            </el-table-column>
            <el-table-column
                prop="entrustOssName"
                label="委托书"
                min-width="200"
                show-overflow-tooltip
            >
                <template slot-scope="scope">
                    <span
                        @click="preview1()"
                        style="color: blue; cursor: pointer; overflow: hidden"
                    >
                        {{ scope.row.entrustOssName }}
                    </span>
                    <el-upload
                        style="margin: 7px 15px 0px 0px"
                        class="upload-demo"
                        :action="uploadUrl"
                        :data="{
                            bucketName,
                            relationId,
                            orgCode
                        }"
                        :before-upload="beforeAvatarUpload"
                        :accept="accept"
                        :on-success="attachOnSuccess"
                        :http-request="uploadBefore"
                        :show-file-list="false"
                        @change="modifyState(row)"
                        name="files"
                    >
                        <img src="@/assets/btn/commit.png" />
                    </el-upload>
                    <img
                    v-if="scope.row.id"
                        src="@/assets/btn/downLoad.png"
                        @click="handleDownload(scope.row)"
                        style="position: absolute; right: 0"
                    />
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import ossRequest from '@/api/oss/oss.js'
import { mapMutations } from 'vuex'
import { bytesToSize, getUuid, batchDownload } from '@/utils/common'
import service from '@/utils/request'
import { showLoading, hideLoading } from '@/utils/common'
// 事实外包方
import correspondentUnit from '@/api/OutsourcingartyAdmin/correspondentUnit/correspondentUnit.js'
export default {
    props: {
        bucketName: {
            type: String,
            default: '',
            require: true
        },
        // 单据id
        billid: {
            type: String,
            default: '',
            require: true
        },
        // 是否需要修改样式
        isTableRowClass: {
            type: Boolean,
            default: false
        },
        // 是否通过验证
        aptitudeSend: {
            type: Boolean,
            default: false
        },
        aptitudeTables: {
            type: Array,
            require: true
        }
    },
    data () {
        return {
            isBatch: false, //是否进入批量操作
            batch: '进入批量管理',
            aptitudeTable: [], //资质信息表格数据
            checkedDetail: [], //选中的数据
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            relationId: '',
            pagination: {
                limit: 10, //	每页显示条数
                name: '', //合同名称
                orgName: '', //机构
                page: 1 //当前页数
            },
            totalPage: 0, //总页数
            rowIndex: '',
            certType: [],
            unWatch: '',
            errorMsg: [], //验证数组
            isShowcertNo: false, //是否禁用证书编号
            deleteDate: {}, //删除对象
            oldDate: [], //列表查回来的基础数据
        }
    },
    created () {
        this.qualificationList(this.billid) //初始化资质信息列表
    },
    computed: {
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    methods: {
        //修改行样式
        tableRowClass ({ row }) {
            if (this.isTableRowClass) {
                return
            } else {
                if (row.state == -1) {
                    return 'red'
                } else if (row.state == 1) {
                    return 'green'
                } else if (row.state == 2) {
                    return 'yellow'
                }
                return ''
            }
        },
        ...mapMutations(['setSelectedInfo']),
        //是否批量管理
        batchOperation () {
            this.isBatch = !this.isBatch
            if (this.isBatch) {
                this.batch = '退出批量管理'
                this.$refs.table.clearSelection()
            } else {
                this.batch = '进入批量管理'
            }
        },
        cellClick (row) {
            //是第几行
            this.rowIndex = this.aptitudeTable.findIndex(x => x === row)
        },
        //委托人添加一行
        aptitudeAddRow () {
            let obj = {
                billId: this.billid, //单据id
                changeType: 1, //操作状态
                entrustOss: '', //委托书
                id: '', //主键
                idCard: '', //身份证号
                idCardOss: '', //身份证附件
                name: '', //	姓名
                originalId: '', //原单id
                phone: '', //手机号
                idCardOssImage: '', //身份证附件图片预览
                entrustOssImage: '', //委托书图片预览
                state: 1,
                idCardOssName: '', //身份证附件
                entrustOssName: '', //委托书
                uuid: getUuid() //本地的uuid区分每条数据
            }
            this.aptitudeTable.push(obj)
        },
        //选中的行
        handleDetailSelectionChange (selection) {
            this.checkedDetail = selection
        },
        //删除一行
        handleDelete (row, $index) {
            if (row.id) {
                if (this.isTableRowClass) {
                    this.clientPop(
                        'info',
                        '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                        this.callback(row)
                    )
                } else {
                    this.clientPop(
                        'info',
                        '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                        this.callbacks(row, $index)
                    )
                }
            } else {
                this.aptitudeTable.splice($index, 1)
            }
        },
        // 编辑删除回调
        callback (row) {
            return () => {
                let data = []
                row.changeType = -1
                // 判断是否是原单数据，【只有变更数据才会有原单id】
                if (row.sourceId) {
                    row.state = -1
                }
                data.push(row)
                this.$emit('getAptitudeData', data)
            }
        },
        // 变更删除回调
        callbacks (row, index) {
            return () => {
                if (!row.newState) {
                    this.aptitudeTable[index].changeType = -1
                    this.aptitudeTable[index].state = -1
                } else {
                    this.aptitudeTable.splice(index, 1)
                }
            }
        },
        // 撤销
        revoke (index) {
            this.aptitudeTable[index].changeType = 0
            this.aptitudeTable[index].state = 1
        },

        //批量删除
        handleBatchDelete () {
            const length = this.checkedDetail.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？`,
                this.delete
            )
        },
        delete () {
            this.checkedDetail.filter(item => {
                // 如果有id ，则改changeType为-1
                if (item.id) {
                    item.changeType = -1
                } else {
                    // 如果没有id，判断uuid是否相同，相同则在原数据删除
                    this.aptitudeTable.map((items, index) => {
                        if (item.uuid == items.uuid) {
                            this.aptitudeTable.splice(index, 1)
                        }
                    })
                }
            })
            // 直接过滤所有无id的数据
            let data = this.checkedDetail.filter(item => {
                if (item.id) {
                    return item
                }
            })
            this.$emit('getAptitudeData', data)
        },

        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        //批量下载
        handleBatchDownload () {
            const fileList = this.attachSelection.map(item => {
                return {
                    objectName: item.objectName,
                    objectPath: item.objectPath
                }
            })
            batchDownload(fileList)
        },
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //委托书上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取委托书上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    res.map(x => {
                        x.fileName = x.objectName
                        x.size = x.objectSize
                        x.founderName = x.ossBucketName
                        return scrollX
                    })
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'entrustOssImage',
                        res[0].objectPath
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'entrustOssName',
                        res[0].objectName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'entrustOss',
                        res[0].relationId
                    )
                    // 上传成功调用变色方法
                    this.modifyState(this.aptitudeTable[this.rowIndex])
                })
        },
        //覆盖默认的委托书上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },

        //身份证附件上传成功
        attachOnSuccessIdCard () {
            this.getObjectByRelationIdCard()
        },
        //获取身份证附件上传成功的对象
        getObjectByRelationIdCard () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    res.map(x => {
                        x.fileName = x.objectName
                        x.size = x.objectSize
                        x.founderName = x.ossBucketName
                        return scrollX
                    })
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'idCardOssImage',
                        res[0].objectPath
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'idCardOss',
                        res[0].relationId
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'idCardOssName',
                        res[0].objectName
                    )
                    // 上传成功调用变色方法
                    this.modifyState(this.aptitudeTable[this.rowIndex])
                })
        },
        //覆盖默认的身份证附件上传行为，可以自定义上传的实现
        uploadBeforeIdCard (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccessIdCard()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //保存
        preserve () {
            this.errorMsg = []
            // 验证是否有数据
            let isStr = false
            this.aptitudeTable.forEach((item, index) => {
                let str1 = `请完善第 ${index + 1} 行的`
                if (item.name === '' || item.name === null) {
                    let str = '姓名,'
                    isStr = true
                    str1 += str
                }
                if (item.phone === '' || item.phone === null) {
                    let str = '手机号,'
                    isStr = true
                    str1 += str
                } else {
                    if (!/^1[3-9]\d{9}$/.test(item.phone)) {
                        let str = '手机号码不正确！'
                        isStr = true
                        str1 += str
                    }
                }
                if (item.idCard === '' || item.idCard === null) {
                    let str = '身份证号,'
                    isStr = true
                    str1 += str
                } else {
                    if (
                        !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(
                            item.idCard
                        )
                    ) {
                        let str = '身份证号码不正确！'
                        isStr = true
                        str1 += str
                    }
                }
                if (item.idCardOssName === '' || item.idCardOssName === null) {
                    let str = '身份证附件,'
                    isStr = true
                    str1 += str
                }
                if (
                    item.entrustOssName === '' ||
                    item.entrustOssName === null
                ) {
                    let str = '委托书,'
                    isStr = true
                    str1 += str
                }

                if (isStr) {
                    this.errorMsg.push(str1)
                }
            })
            if (this.errorMsg.length > 0) {
                this.$emit('update:aptitudeSend', false)
                this.$emit('setError', 'aptitude')
                return
            } else {
                if (this.aptitudeTable.length > 0) {
                    this.$emit('update:aptitudeSend', true)
                    this.$emit('update:aptitudeTables', this.aptitudeTable)
                } else {
                    this.$emit('update:aptitudeSend', false)
                    this.errorMsg.push('请至少包含一条数据')
                    this.$emit('setError', 'aptitude')
                }
            }
        },
        // 资质信息列表
        async qualificationList (val) {
            // 如果有isTableRowClass，则调编辑页面的资质接口，否则调变更页面的资质接口
            let data = []
            if (this.isTableRowClass) {
                data = await correspondentUnit.getCorrespondentUnitDetailed({
                    id: val
                })
            } else {
                data =
                    await correspondentUnit.getCorrespondentUnitChangeDetailed({
                        id: val
                    })
            }
            if (data.code != 200) {
                this.aptitudeTable = data
                this.oldDate = JSON.parse(JSON.stringify(data))
            }
        },
        // 修改样式
        modifyState (row) {
            this.oldDate.map(item => {
                if (item.id == row.id && row.originalId) {
                    // if( !this.isObjectValueEqual(item, row)) {
                    this.aptitudeTable.map(items => {
                        if (items.id == row.id) {
                            return (items.state = 2)
                        }
                    })
                    // }
                }
            })
        },
        //预览附件
        preview () {
            if (this.aptitudeTable[this.rowIndex].idCardOssImage) {
                window.open(this.aptitudeTable[this.rowIndex].idCardOssImage)
            } else {
                this.clientPop('err', '请先上传附件')
            }
        },
        //委托书预览附件
        preview1 () {
            if (this.aptitudeTable[this.rowIndex].entrustOssImage) {
                window.open(this.aptitudeTable[this.rowIndex].entrustOssImage)
            } else {
                this.clientPop('err', '请先上传附件')
            }
        },
        //下载某一行
        async handleDownload (obj) {
            showLoading()
            const url = obj.entrustOssImage
            const fileNameFull = obj.entrustOssName
            const fileExt = fileNameFull.split('.').pop()
            if (
                ['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(
                    fileExt.toLowerCase()
                ) === -1
            ) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
            hideLoading()
        },
        //下载某一行
        async handleDownload1 (obj) {
            showLoading()
            const url = obj.idCardOssImage
            const fileNameFull = obj.idCardOssName
            const fileExt = fileNameFull.split('.').pop()
            if (
                ['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(
                    fileExt.toLowerCase()
                ) === -1
            ) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
            hideLoading()
        },
        downloadIamge (imgsrc, fileName) {
            //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {
                    // if browser is IE
                    navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        }
    },
}
</script>

<style lang="scss" scoped>
.handle {
    display: flex;
    align-items: center;
    text-align: left;
    div {
        cursor: pointer;
    }
    .download {
        font-size: 23px;
        font-weight: bold;
        color: rgb(122, 168, 24);
    }
}
::v-deep .upload-demo {
    width: 20px;
    margin-left: 2px;
}
::v-deep .cell {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>
